package com.ysjweb.dish.Filter;

import com.alibaba.fastjson2.JSON;
import com.ysjweb.dish.pojo.RequestWrapper;
import com.ysjweb.dish.pojo.Result;
import com.ysjweb.dish.pojo.UserInformation;
import com.ysjweb.dish.tool.JwtTool;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*", asyncSupported = true)
@Order(1)
public class login implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        response.setHeader("Access-Control-Allow-Origin", "http://localhost:8080");//具体域名
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,userInformation,token,PictureUrl,VideoUrl");
        response.addHeader("Access-Control-Expose-Headers", "userInformation,token,PictureUrl,VideoUrl");
        response.setHeader("Cache-Control", "no-cache"); // 禁止缓存
        response.setHeader("Connection", "keep-alive"); // 保持连接

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        //判断是否是登录/注册操作
        //通过url判断是否是登录操作//如果是直接放行
        String url=request.getRequestURL().toString();
            if (url.contains("login") || url.contains("register")) {
                log.info("login/register操作");
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
            //如果不是检查是否由令牌
            //通过请求头获取令牌
            String header = request.getHeader("Authorization");
            String jwt="";
            if(header!=null&&header.startsWith("Bearer ")){
                jwt=header.substring(7);
            }
//            String jwt = request.getHeader("token");
//            String jwt=response.getHeader("token");
            if(jwt==null){
                log.info("jwt为null");
            }
            Claims claims;
            try {
                claims = JwtTool.parseJwt(jwt);//如果解析失败就说明令牌不合法
            } catch (Exception e) {
                log.info("未登录");
                Result error = new Result(0, "NO_LOGIN", null);//这个是和前端约定好的,只要看见这个信息就会跳转到登录页面
                String transform = JSON.toJSONString(error);
                //如果想在过滤器中响应,则需要对 ServletResponse/HttpServletRequest对应的对象进行修改/操作
                //先调用getWriter获取 输出流
                response.getWriter().write(transform);
                return;
            }
            Integer id = claims.get("id", Integer.class);
            UserInformation userInformation = new UserInformation();
            userInformation.setId(id);
            String InformationJson = JSON.toJSONString(userInformation);
            RequestWrapper requestWrapper = new RequestWrapper(request);
            requestWrapper.addHeader("userInformation", InformationJson);
//            request.setAttribute("userInformation", id);
            //传输用户信息
            response.setHeader("userInformation", id.toString());

            log.info("令牌合法");
            filterChain.doFilter(requestWrapper, servletResponse);

    }
}
